// Author: wsfuyibing <682805@qq.com>
// Date: 2025-06-24

package load

import (
	"context"
	"gitee.com/go-libs/db-xorm/db"
	"gitee.com/go-libs/log"
	"server/app/http/models"
	"server/app/kind"
	"server/app/lib/user_balance/operations"
	"sync"
)

var (
	once     = new(sync.Once)
	operator *Operator
)

// Operator
// 加载余额.
type Operator struct {
	operations.Operations
}

// New
// 获取单例.
func New() *Operator { return operator }

// Run
// 执行逻辑.
func (o *Operator) Run(ctx context.Context, sess *db.Session, uid kind.UserId) (model *models.UserStatistic, err error) {
	var (
		has, repair bool
		latest      kind.Balance
		record      *models.BalanceRecords
	)

	// 1. 读取统计.
	if model, err = o.GetUserStatistic(ctx, sess, uid); err != nil {
		return
	} else {
		log.Infofc(ctx, `[lib][balance][user] 可用余额: balance="%v"`, model.Balance)
	}

	// 2. 读取流水.
	if record, has, err = o.GetLatestRecord(ctx, sess, uid); err != nil {
		return
	}

	// 3. 对比余额.
	if has {
		log.Infofc(ctx, `[lib][balance][user] 最后流水: id="%v", balance="%v"`, record.Id, record.Balance)
		// 3.1 修复 1.
		//     用户统计中记录的余额和流水的最后一条记录不一样.
		if !model.Balance.Equal(record.Balance) {
			latest = record.Balance
			repair = true
		}
	} else {
		log.Infofc(ctx, `[lib][balance][user] 无流水账`)
		// 3.2 修复 2.
		//     用户统计中记录的余额有值但无流水.
		if !model.Balance.IsZero() {
			latest = 0
			repair = true
		}
	}

	// 5. 修复记录.
	//    若没有流水里没有该用户的最后, 则视为统计数据不准.
	if repair {
		err = o.SetUserBalance(ctx, sess, uid, latest)
	}
	return
}

func init() {
	once.Do(func() {
		operator = &Operator{}
	})
}
